import React, { useState, useCallback, useEffect } from "react";
import { Layout, Typography, message, Spin, ConfigProvider, theme } from "antd";
import { BrowserRouter as Router } from "react-router-dom";
import "./App.css";
import { generateStyledImage } from "./services/aiService";
import AppRoutes from "./routes";
import { ThemeProvider, useTheme } from "./context/ThemeContext";

const { Content } = Layout;
const { Title } = Typography;

function AppContent() {
  const { isDark, antdThemeConfig } = useTheme();
  const [uploadedImage, setUploadedImage] = useState(null);
  const [selectedStyle, setSelectedStyle] = useState("none");
  const [textPrompt, setTextPrompt] = useState("");
  const [resultImage, setResultImage] = useState(null);
  const [isGenerating, setIsGenerating] = useState(false);
  const [generationProgress, setGenerationProgress] = useState(0);
  const [error, setError] = useState(null);
  const [appReady, setAppReady] = useState(false);

  // 应用加载动画
  useEffect(() => {
    const timer = setTimeout(() => {
      setAppReady(true);
    }, 500);
    return () => clearTimeout(timer);
  }, []);

  // 创建全局消息通知样式
  useEffect(() => {
    message.config({
      top: 80,
      duration: 3,
      maxCount: 3,
    });
  }, []);

  // 优化：根据风格选择自动提供文本建议
  useEffect(() => {
    if (selectedStyle !== "none" && selectedStyle !== "custom") {
      const styleSuggestions = {
        miyazaki: `使用日本动漫中标志性的明亮色彩和温暖氛围，加入丰富的自然元素和细节`,
        lego: "乐高积木风格，色彩鲜明，块状结构清晰",
        pixar: "皮克斯3D动画风格，光滑细腻的渲染效果",
        disney: "迪士尼动画风格，充满童话感和快乐氛围",
      };

      setTextPrompt(styleSuggestions[selectedStyle] || "");
    }
  }, [selectedStyle]);

  // 模拟进度条更新
  const simulateProgress = useCallback(() => {
    const calculateNextProgress = (current) => {
      if (current >= 95) return 95;

      // 在不同阶段使用不同的增长速度
      if (current < 30) return Math.floor(current + Math.random() * 5 + 3);
      if (current < 60) return Math.floor(current + Math.random() * 3 + 2);
      if (current < 85) return Math.floor(current + Math.random() * 2 + 1);
      return Math.floor(current + Math.random() * 1 + 0.5);
    };

    const interval = setInterval(() => {
      setGenerationProgress((prev) => {
        const next = calculateNextProgress(prev);
        return Math.min(95, next);
      });
    }, 300);

    return interval;
  }, []);

  // 图像生成函数
  const generateImage = useCallback(async () => {
    // 验证输入
    if (!uploadedImage) {
      message.error("请先上传图片");
      return;
    }

    if (selectedStyle === "custom" && !textPrompt.trim()) {
      message.warning("使用自定义风格时，请提供文字描述");
      return;
    }

    setError(null);
    setIsGenerating(true);
    setGenerationProgress(0);

    // 启动进度条动画
    const progressInterval = simulateProgress();

    try {
      // 调用AI服务生成图像
      const generatedImageUrl = await generateStyledImage(
        uploadedImage,
        textPrompt,
        selectedStyle
      );

      // 设置进度为100%
      clearInterval(progressInterval);
      setGenerationProgress(100);

      // 设置结果图像
      setResultImage(generatedImageUrl);

      message.success({
        content: "图像生成成功！",
        icon: (
          <span role="img" aria-label="success">
            ✨
          </span>
        ),
      });
    } catch (err) {
      clearInterval(progressInterval);
      setError(err.message || "图像生成失败，请重试");
      message.error({
        content: err.message || "图像生成失败，请重试",
        icon: (
          <span role="img" aria-label="error">
            ❌
          </span>
        ),
      });
    } finally {
      setIsGenerating(false);
    }
  }, [uploadedImage, selectedStyle, textPrompt, simulateProgress]);

  // 处理重置功能
  const handleReset = useCallback(() => {
    setUploadedImage(null);
    setSelectedStyle("none");
    setTextPrompt("");
    setResultImage(null);
    setError(null);
    message.info("已重置所有设置");
  }, []);

  if (!appReady) {
    return (
      <div className="app-loading">
        <Spin size="large" />
        <p>加载中...</p>
      </div>
    );
  }

  return (
    <ConfigProvider theme={antdThemeConfig}>
      <Router>
        <AppRoutes />
      </Router>
    </ConfigProvider>
  );
}

function App() {
  return (
    <ThemeProvider>
      <AppContent />
    </ThemeProvider>
  );
}

export default App;
